package com.ruoyi.hxf.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Arrays;

import com.ruoyi.hxf.domain.Course;
import com.ruoyi.hxf.domain.Teacher;
import com.ruoyi.hxf.domain.TeacherCourse;
import com.ruoyi.hxf.domain.Type;
import com.ruoyi.hxf.mapper.RosterMapper;
import com.ruoyi.hxf.mapper.TypeMapper;
import com.ruoyi.system.domain.App;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;

import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.hxf.domain.vo.TypeVo;
import com.ruoyi.hxf.domain.bo.TypeBo;
import com.ruoyi.hxf.service.ITypeService;

/**
 * 班级创建管理
 *
 * @author hxf
 * @date 2022-12-15
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/class/type")
public class TypeController extends BaseController {
    private final ISysUserService userService;
    private final ITypeService iTypeService;
    private final RosterMapper rosterMapper;
    private final TypeMapper typeMapper;

    /**
     * 查询班级创建管理列表
     */
//    @SaCheckPermission("class:type:list")
    @GetMapping("/list")
    public R<List<TypeVo>> list(TypeBo bo) {
        List<TypeVo> list = iTypeService.queryList(bo);
        for (TypeVo typeVo : list) {
            if (typeVo.getClassLeader() != null) {
                typeVo.setClassLeaderName(typeMapper.selectClassLeaderName(typeVo.getClassLeader()));
            }
        }
        return R.ok(list);
    }

    /**
     * 手机端级联
     * @param bo
     * @return
     */
    @GetMapping("/AppList")
    public R<List<TypeVo>> AppList(TypeBo bo) {
        List<TypeVo> list = iTypeService.queryList(bo);
        List<TypeVo> newList = new ArrayList<>();
        for (TypeVo typeVo : list) {
            if (typeVo.getClassLeader() != null) {
                typeVo.setClassLeaderName(typeMapper.selectClassLeaderName(typeVo.getClassLeader()));

            }
            if(String.valueOf(typeVo.getParentId()).equals("0")||typeVo.getClassLeader() != null){
                newList.add(typeVo);
            }
        }

        return R.ok(newList);
    }
    /**
     * 查询班级创建管理列表
     */
//    @SaCheckPermission("class:type:list")
    @GetMapping("/homeWorkClass/{classId}")
    public String getHomeWorkClass(@PathVariable("classId") Long classId) {
        return rosterMapper.selectClassName(classId);
    }
    /**
     * 导出班级创建管理列表
     */
//    @SaCheckPermission("class:type:export")
    @Log(title = "班级创建管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TypeBo bo, HttpServletResponse response) {
        List<TypeVo> list = iTypeService.queryList(bo);
        ExcelUtil.exportExcel(list, "班级创建管理", TypeVo.class, response);
    }

    /**
     * 获取班级创建管理详细信息
     *
     * @param typeId 主键
     */
//    @SaCheckPermission("class:type:query")
    @GetMapping("/{typeId}")
    public R<TypeVo> getInfo(@NotNull(message = "主键不能为空")
                             @PathVariable Long typeId) {
        return R.ok(iTypeService.queryById(typeId));
    }

    /**
     * 新增班级创建管理
     */
//    @SaCheckPermission("class:type:add")
    @Log(title = "班级创建管理", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TypeBo bo) {
        Type type = iTypeService.selectByDeptId(bo.getDeptId());
        if(type!=null){
            return R.ok("error");
        }else {
            return toAjax(iTypeService.insertByBo(bo));
        }

    }

    /**
     * 修改班级创建管理
     */
//    @SaCheckPermission("class:type:edit")
    @Log(title = "班级创建管理", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TypeBo bo) {
        if (bo.getStatus().equals("1")) {
            typeMapper.deleteClassTeacher(bo.getDeptId());
            List<Course> courses = rosterMapper.listClassCourse(String.valueOf(bo.getDeptId()));
            for (Course course : courses) {
                Long iDelOne = rosterMapper.selectTeacherId(course.getOneT(), course.getOneS());
                if (iDelOne != null) {
                    TeacherCourse teacherCourseDelOne = new TeacherCourse();
                    teacherCourseDelOne.setId(course.getId());
                    teacherCourseDelOne.setLabel(course.getLabel());
                    teacherCourseDelOne.setTeacherId(Long.valueOf(iDelOne));
                    teacherCourseDelOne.setOneC(null);
                    rosterMapper.updateTeacherCourseOne(teacherCourseDelOne.getOneC(), teacherCourseDelOne.getId(), teacherCourseDelOne.getLabel(), teacherCourseDelOne.getTeacherId());
                }
                Long iDelTwo = rosterMapper.selectTeacherId(course.getTwoT(), course.getTwoS());
                if (iDelTwo != null) {
                    TeacherCourse teacherCourseDelTwo = new TeacherCourse();
                    teacherCourseDelTwo.setId(course.getId());
                    teacherCourseDelTwo.setLabel(course.getLabel());
                    teacherCourseDelTwo.setTeacherId(Long.valueOf(iDelTwo));
                    teacherCourseDelTwo.setTwoC(null);
                    rosterMapper.updateTeacherCourseTwo(teacherCourseDelTwo.getTwoC(), teacherCourseDelTwo.getId(), teacherCourseDelTwo.getLabel(), teacherCourseDelTwo.getTeacherId());
                }
                Long iDelThree = rosterMapper.selectTeacherId(course.getThreeT(), course.getThreeS());
                if (iDelThree != null) {
                    TeacherCourse teacherCourseDelThree = new TeacherCourse();
                    teacherCourseDelThree.setId(course.getId());
                    teacherCourseDelThree.setLabel(course.getLabel());
                    teacherCourseDelThree.setTeacherId(Long.valueOf(iDelThree));
                    teacherCourseDelThree.setThreeC(null);
                    rosterMapper.updateTeacherCourseThree(teacherCourseDelThree.getThreeC(), teacherCourseDelThree.getId(), teacherCourseDelThree.getLabel(), teacherCourseDelThree.getTeacherId());
                }
                Long iDelFour = rosterMapper.selectTeacherId(course.getFourT(), course.getFourS());
                if (iDelFour != null) {
                    TeacherCourse teacherCourseDelFour = new TeacherCourse();
                    teacherCourseDelFour.setId(course.getId());
                    teacherCourseDelFour.setLabel(course.getLabel());
                    teacherCourseDelFour.setTeacherId(Long.valueOf(iDelFour));
                    teacherCourseDelFour.setFourC(null);
                    rosterMapper.updateTeacherCourseFour(teacherCourseDelFour.getFourC(), teacherCourseDelFour.getId(), teacherCourseDelFour.getLabel(), teacherCourseDelFour.getTeacherId());
                }
                Long iDelFive = rosterMapper.selectTeacherId(course.getFiveT(), course.getFiveS());
                if (iDelFive != null) {
                    TeacherCourse teacherCourseDelFive = new TeacherCourse();
                    teacherCourseDelFive.setId(course.getId());
                    teacherCourseDelFive.setLabel(course.getLabel());
                    teacherCourseDelFive.setTeacherId(Long.valueOf(iDelFive));
                    teacherCourseDelFive.setFiveC(null);
                    rosterMapper.updateTeacherCourseFive(teacherCourseDelFive.getFiveC(), teacherCourseDelFive.getId(), teacherCourseDelFive.getLabel(), teacherCourseDelFive.getTeacherId());
                }
                Long iDelSix = rosterMapper.selectTeacherId(course.getSixT(), course.getSixS());
                if (iDelSix != null) {
                    TeacherCourse teacherCourseDelSix = new TeacherCourse();
                    teacherCourseDelSix.setId(course.getId());
                    teacherCourseDelSix.setLabel(course.getLabel());
                    teacherCourseDelSix.setTeacherId(Long.valueOf(iDelSix));
                    teacherCourseDelSix.setSixC(null);
                    rosterMapper.updateTeacherCourseSix(teacherCourseDelSix.getSixC(), teacherCourseDelSix.getId(), teacherCourseDelSix.getLabel(), teacherCourseDelSix.getTeacherId());
                }
            }
            rosterMapper.deleteWithValidByIds(String.valueOf(bo.getDeptId()));
        }
        return toAjax(iTypeService.updateByBo(bo));
    }

    /**
     * 删除班级创建管理
     *
     * @param typeIds 主键串
     */
//    @SaCheckPermission("class:type:remove")
    @Log(title = "班级创建管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{typeIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] typeIds) {

        for (Long typeId : typeIds) {
            typeMapper.deleteClassTeacher(typeId);
            List<Course> courses = rosterMapper.listClassCourse(String.valueOf(typeId));
            for (Course course : courses) {
                Long iDelOne = rosterMapper.selectTeacherId(course.getOneT(), course.getOneS());
                if (iDelOne != null) {
                    TeacherCourse teacherCourseDelOne = new TeacherCourse();
                    teacherCourseDelOne.setId(course.getId());
                    teacherCourseDelOne.setLabel(course.getLabel());
                    teacherCourseDelOne.setTeacherId(Long.valueOf(iDelOne));
                    teacherCourseDelOne.setOneC(null);
                    rosterMapper.updateTeacherCourseOne(teacherCourseDelOne.getOneC(), teacherCourseDelOne.getId(), teacherCourseDelOne.getLabel(), teacherCourseDelOne.getTeacherId());
                }
                Long iDelTwo = rosterMapper.selectTeacherId(course.getTwoT(), course.getTwoS());
                if (iDelTwo != null) {
                    TeacherCourse teacherCourseDelTwo = new TeacherCourse();
                    teacherCourseDelTwo.setId(course.getId());
                    teacherCourseDelTwo.setLabel(course.getLabel());
                    teacherCourseDelTwo.setTeacherId(Long.valueOf(iDelTwo));
                    teacherCourseDelTwo.setTwoC(null);
                    rosterMapper.updateTeacherCourseTwo(teacherCourseDelTwo.getTwoC(), teacherCourseDelTwo.getId(), teacherCourseDelTwo.getLabel(), teacherCourseDelTwo.getTeacherId());
                }
                Long iDelThree = rosterMapper.selectTeacherId(course.getThreeT(), course.getThreeS());
                if (iDelThree != null) {
                    TeacherCourse teacherCourseDelThree = new TeacherCourse();
                    teacherCourseDelThree.setId(course.getId());
                    teacherCourseDelThree.setLabel(course.getLabel());
                    teacherCourseDelThree.setTeacherId(Long.valueOf(iDelThree));
                    teacherCourseDelThree.setThreeC(null);
                    rosterMapper.updateTeacherCourseThree(teacherCourseDelThree.getThreeC(), teacherCourseDelThree.getId(), teacherCourseDelThree.getLabel(), teacherCourseDelThree.getTeacherId());
                }
                Long iDelFour = rosterMapper.selectTeacherId(course.getFourT(), course.getFourS());
                if (iDelFour != null) {
                    TeacherCourse teacherCourseDelFour = new TeacherCourse();
                    teacherCourseDelFour.setId(course.getId());
                    teacherCourseDelFour.setLabel(course.getLabel());
                    teacherCourseDelFour.setTeacherId(Long.valueOf(iDelFour));
                    teacherCourseDelFour.setFourC(null);
                    rosterMapper.updateTeacherCourseFour(teacherCourseDelFour.getFourC(), teacherCourseDelFour.getId(), teacherCourseDelFour.getLabel(), teacherCourseDelFour.getTeacherId());
                }
                Long iDelFive = rosterMapper.selectTeacherId(course.getFiveT(), course.getFiveS());
                if (iDelFive != null) {
                    TeacherCourse teacherCourseDelFive = new TeacherCourse();
                    teacherCourseDelFive.setId(course.getId());
                    teacherCourseDelFive.setLabel(course.getLabel());
                    teacherCourseDelFive.setTeacherId(Long.valueOf(iDelFive));
                    teacherCourseDelFive.setFiveC(null);
                    rosterMapper.updateTeacherCourseFive(teacherCourseDelFive.getFiveC(), teacherCourseDelFive.getId(), teacherCourseDelFive.getLabel(), teacherCourseDelFive.getTeacherId());
                }
                Long iDelSix = rosterMapper.selectTeacherId(course.getSixT(), course.getSixS());
                if (iDelSix != null) {
                    TeacherCourse teacherCourseDelSix = new TeacherCourse();
                    teacherCourseDelSix.setId(course.getId());
                    teacherCourseDelSix.setLabel(course.getLabel());
                    teacherCourseDelSix.setTeacherId(Long.valueOf(iDelSix));
                    teacherCourseDelSix.setSixC(null);
                    rosterMapper.updateTeacherCourseSix(teacherCourseDelSix.getSixC(), teacherCourseDelSix.getId(), teacherCourseDelSix.getLabel(), teacherCourseDelSix.getTeacherId());
                }
            }
            rosterMapper.deleteWithValidByIds(String.valueOf(typeId));
        }
        return toAjax(iTypeService.deleteWithValidByIds(Arrays.asList(typeIds), true));
    }

    /**
     * 修改班级班主任管理
     */
//    @SaCheckPermission("class:type:edit")
    @Log(title = "修改班级班主任管理", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/leaderName/{classId}/{classLeaderName}")
    public R<Void> editClassLeaderName(@PathVariable("classId") Long classId, @PathVariable("classLeaderName") String userName) {
        String s=iTypeService.selectRoleName();
        if(s==null){
            return R.fail("请先添加角色(班主任)");
        }
        Long OldClassLeader=iTypeService.selectTypeByDeptId(classId);
        if(OldClassLeader!=null){
            iTypeService.updateUserRole(OldClassLeader,s);
            App app = userService.selectAppUserByClassId(OldClassLeader);
            if(app!=null){
                String classIds = app.getClassId();
                StringBuffer appList=new StringBuffer();
                if(classIds.length()!=0){
                    String[] split = classIds.split(",");
                    for (int i = 0; i < split.length; i++) {
                        if(Integer.parseInt(split[i])!=classId){
                            appList.append(split[i]+",");
                        }
                    }
                    userService.updateUserByApp(appList.substring(0,appList.length()-1),OldClassLeader);
                }
            }
        }

        if (!userName.equals("不要班主任了!")) {
            Long aLong = rosterMapper.selectUserByNameId(userName);
            Type type = new Type();
            type.setDeptId(classId);
            type.setClassLeader(String.valueOf(aLong));
            App app = userService.selectAppUserByClassId(rosterMapper.selectUserByNameId(userName));
            if(app!=null){
                String classIds = app.getClassId();
                StringBuffer appList=new StringBuffer();
                if(classIds.length()!=0){
                    String[] split = classIds.split(",");
                    for (int i = 0; i < split.length; i++) {
                            appList.append(split[i]+",");
                    }
                    appList.append(classId);
                    userService.updateUserByApp(String.valueOf(appList),aLong);
                }
            }
            iTypeService.insertUserRole(aLong,s);
            return toAjax(iTypeService.updateByType(type));
        } else {
            Type typeClearLeader = new Type();
            typeClearLeader.setDeptId(classId);
            typeClearLeader.setClassLeader(null);
            return toAjax(iTypeService.updateByType(typeClearLeader));
        }
    }

}
